﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;

namespace Sykj.Services
{
    /// <summary>
    /// 栏目信息
    /// </summary>
    public class Channel : Sykj.Repository.RepositoryBase<Sykj.Entity.Channel>, Sykj.IServices.IChannel
    {
        public Channel(Sykj.Repository.SyDbContext dbcontext) : base(dbcontext)
        {

        }

        /// <summary>
        /// 创建栏目
        /// </summary>
        /// <param name="model">栏目模型</param>
        /// <returns>成功返回分类Id，失败返回0</returns>
        public bool CreateChannel(Entity.Channel model)
        {
            try
            {
                model.CreateDate = DateTime.Now;
                int channelId = model.ChannelId;
                model.ChannelId = 0;
                Add(model);
                //获得父级商品分类
                var parentModel = GetModel(c => c.ChannelId == model.ParentId);
                //存在父级分类
                if (parentModel != null)
                {
                    // 设置父级有子级
                    if (!parentModel.IsHasChildren)
                    {
                        parentModel.IsHasChildren = true;
                        Update(parentModel);
                    }

                    model.Depth = parentModel.Depth + 1;
                    model.Path = parentModel.Path + "|" + model.ChannelId;
                }
                else
                {
                    model.Depth = 1;
                    model.Path = model.ChannelId.ToString();
                }
                model.IsHasChildren = false;
                model.Sort = GetRecordCount($" ParentId={model.ParentId}") + 1;

                Update(model);

                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }
    }
}